package org.gogenie.android.ui;

import java.io.File;

import org.gogenie.android.model.Post;

import uy.com.silveira.noname.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * Here the user selects if they want to take/select a picture or just type.
 * @author jjso
 */
public class InputChoiceActivity extends Activity {

  public static String EXTRA_POST = "Post";

  private static int IMAGE_CAPTURE_REQUEST = 1;
  private static final String CAPTURE_JPG = "Capture.jpg";

  private Post post;

  private OnClickListener takePictureClickListener = new OnClickListener() {
    public void onClick(View v) {
      Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      // TODO(jjso): check that we have external store with Environment.getExternalStorageState
      takePicture.putExtra(MediaStore.EXTRA_OUTPUT,
          Uri.fromFile(new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), CAPTURE_JPG)));
      startActivityForResult(takePicture, IMAGE_CAPTURE_REQUEST);
    }
  };

  private OnClickListener justTextClickListener = new OnClickListener() {
    public void onClick(View v) {
      openEnterText();
    }
  };

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.input_choice);
    ((Button) findViewById(R.id.take_picture_btn)).setOnClickListener(takePictureClickListener);
    ((Button) findViewById(R.id.just_text_btn)).setOnClickListener(justTextClickListener);

    post = (Post) getIntent().getSerializableExtra(EXTRA_POST);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d("NoName", "onActivityResult");
    if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_CAPTURE_REQUEST) {
      File capturedFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), CAPTURE_JPG);
      if (data != null) {
        Log.d("NoName", "There's some data in here!");
      }
      if (capturedFile.exists() && capturedFile.canRead()) {
        Log.d("NoName", "It looks like we have a file");
        // TODO(jjso): storing the file object itself might not be so smart. Serializing?
        post.setImagePath(capturedFile.getPath());
      } else {
        Log.d("NoName", "Where did that file go to?");
      }
      openEnterText();
    }
  }

  private void openEnterText() {
    Intent openEnterTextActivity = new Intent(this, EnterTextActivity.class);
    openEnterTextActivity.putExtra(EnterTextActivity.EXTRA_POST, post);
    startActivity(openEnterTextActivity);
  }
}
